<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useChatStore } from '@/stores/chat'

const chatStore = useChatStore()
const { chatList: messages, messageCount } = storeToRefs(chatStore)
const { addChatItem: addMessage, clearChatList: clearMessages, setResponding: setLoading } = chatStore

const inputText = ref('')
const messagesContainer = ref<HTMLElement>()
const isLoading = ref(false)

const sendMessage = async () => {
  if (!inputText.value.trim())
    return

  const userMessage = inputText.value
  inputText.value = ''

  // 添加用户消息
  addMessage({
    id: Date.now().toString(),
    content: userMessage,
    isAnswer: false,
  })

  // 滚动到底部
  await scrollToBottom()

  // 模拟AI回复
  setLoading(true)
  setTimeout(() => {
    addMessage({
      id: (Date.now() + 1).toString(),
      content: `收到您的消息："${userMessage}"。这是一个模拟回复。`,
      isAnswer: true,
    })
    setLoading(false)
    scrollToBottom()
  }, 1000 + Math.random() * 2000)
}

const startNewConversation = () => {
  clearMessages()
  addMessage({
    id: Date.now().toString(),
    content: '您好！我是您的智能助手，有什么可以帮助您的吗？',
    isAnswer: true,
  })
}

const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value)
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
}

onMounted(() => {
  if (messages.value.length === 0)
    startNewConversation()
})
</script>

<template>
  <div class="flex h-screen bg-gray-100">
    <!-- 侧边栏 -->
    <div class="w-64 bg-white shadow-lg">
      <div class="p-4 border-b">
        <h2 class="text-lg font-semibold text-gray-800">
          对话列表
        </h2>
      </div>
      <div class="p-4">
        <button
          class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition duration-200"
          @click="startNewConversation"
        >
          新建对话
        </button>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="flex-1 flex flex-col">
      <!-- 聊天头部 -->
      <div class="bg-white shadow-sm border-b px-6 py-4">
        <div class="flex items-center justify-between">
          <h1 class="text-xl font-semibold text-gray-800">
            智能助手
          </h1>
          <div class="flex items-center space-x-2">
            <span class="text-sm text-gray-500">{{ messageCount }} 条消息</span>
            <button
              class="text-gray-400 hover:text-red-500 transition duration-200"
              @click="clearMessages"
            >
              清空
            </button>
          </div>
        </div>
      </div>

      <!-- 消息列表 -->
      <div ref="messagesContainer" class="flex-1 overflow-y-auto p-6 space-y-4">
        <div
          v-for="message in messages"
          :key="message.id"
          class="flex" :class="[
            message.isAnswer ? 'justify-end' : 'justify-start',
          ]"
        >
          <div
            class="max-w-xs lg:max-w-md px-4 py-2 rounded-lg" :class="[
              message.isAnswer
                ? 'bg-blue-600 text-white'
                : 'bg-white text-gray-800 shadow-sm',
            ]"
          >
            <p class="text-sm">
              {{ message.content }}
            </p>
          </div>
        </div>

        <!-- 加载指示器 -->
        <div v-if="isLoading" class="flex justify-start">
          <div class="bg-white text-gray-800 shadow-sm max-w-xs lg:max-w-md px-4 py-2 rounded-lg">
            <div class="flex items-center space-x-2">
              <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600" />
              <span class="text-sm">正在输入...</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="bg-white border-t px-6 py-4">
        <div class="flex space-x-4">
          <input
            v-model="inputText"
            type="text"
            placeholder="输入消息..."
            class="flex-1 border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            :disabled="isLoading"
            @keyup.enter="sendMessage"
          >
          <button
            :disabled="isLoading || !inputText.trim()"
            class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white font-medium py-2 px-6 rounded-lg transition duration-200"
            @click="sendMessage"
          >
            发送
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
